<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  install
 */

class m_install_services_InstallService extends f_core_Service
{
    /**
	 * @var m_install_services_InstallService
	 */
	private static $instance;

	/**
	 * Constructor
	 */
	private function __construct()
	{
		// Code if needed...
	}

	/**
	 * @return m_install_services_InstallService
	 */
	public static function getInstance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}

    public function initDb()
    {
        f_builder_DatabaseBuilder::getInstance()->createInitialDatabaseTables();
        $this->generateAllDbTables();
    }

    private function generateAllDbTables()
    {
        $fileResolver = f_file_Resolver::getInstance();

        $files = array();

        $files1 = $fileResolver->fromDirectory(MODULES_DIR)
                ->setMask("documents".DS."*.xml")
                ->setRecursive(true)
                ->find();

        if(count($files1) >= 1)
        {
            foreach($files1 as $file)
            {
                $file = $fileResolver->getOverload($file);
                $xmlFileObject = f_xml_Xpath::getInstance($file);
                $tablebuilder = f_builder_DatabaseBuilder::getInstance()->setXmlObject($xmlFileObject)->createDocumentTable();
                f_builder_DocumentBuilder::getInstance($xmlFileObject)->build();
            }
        }

        $files2 = $fileResolver->fromDirectory(WEBAPP_MODULES_DIR)
        ->setMask("documents".DS."*.xml")
        ->setRecursive(true)
        ->find();

        if(count($files2) >= 1)
        {
            foreach($files2 as $file)
            {
                $xmlFileObject = f_xml_Xpath::getInstance($file);
                $builder = f_builder_DocumentBuilder::getInstance($xmlFileObject);
                $builder->isInWebapp(true)->build();
                $tablebuilder = f_builder_DatabaseBuilder::getInstance()->setXmlObject($xmlFileObject)->createDocumentTable();
            }
        }
    }

    public function checkInstall()
    {
        if(!f_database_Provider::checkConnect() || !f_database_Provider::getInstance()->tableExists('m_users__group'))
        {
            return false;
        }
        return true;
    }
}